package com.itheima.reggie.exceptionHandler;


import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;


@ControllerAdvice(annotations= RestController.class)
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({SQLIntegrityConstraintViolationException.class})
    @ResponseBody
    @ResponseStatus
    public R getMsgHandler(SQLIntegrityConstraintViolationException ex){
        log.info("捕获到异常信息：{}",ex.getMessage());
        boolean contains = ex.getMessage().contains("Duplicate entry");
        if(contains){
            String[] strings = ex.getMessage().split(" ");
            String userName = strings[2];
            String msg = "账号：" + userName + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }


    @ExceptionHandler({CustomException.class})
    @ResponseBody
    @ResponseStatus
    public R getMsgHandler(CustomException e){
        log.info("捕获到异常信息：{}",e.getMessage());
        return R.error(e.getMessage());
    }



}
